from amplitude.dict import Dict

class Controller(Dict):
    """Base class for controllers, if controller.method routing is your thing.
    >>> ctrl = Controller()
    """
    actions = []
    def __init__(c, req, response, template_lookup, **args):
        """base for all controllers, one instance per request.
            req: a request object.
            response: a response object.
            template_lookup: a template_lookup object.
            args: any other keyword arguments.
        """
        Dict.__init__(c, **args)
        c.DEBUG = c.config and c.config.Site and c.config.Site.debug and eval(c.config.Site.debug)
        #if c.DEBUG: print c.__class__.__name__+'.__init__()'
        c.req = req
        c.response = response
        c.template_lookup = template_lookup

    def __call__(c, req):
        # basic call method: returns the result of the given action in req.route
        if req.route.action in [method for method in dir(c) if callable(getattr(c, method))]:
            return eval("c.%s(req)" % req.route.action)
        else:
            return c.not_found()
        
    def render(c, template_path, **args):
        """render the given template using a c.lookup for template lookup."""
        template = c.template_lookup.get_template(template_path)
        if c.response.get_header('Content-Type') == []:
            c.response.set_header('Content-Type', 'text/html')
        return template.render(c=c, req=c.req, response=c.response, **args)
        
    # convenience methods
    def not_implemented(c):
        c.response.not_implemented()
        return c.render('/errors/notimplemented.mako')
        
    def not_found(c):
        c.response.not_found()
        return c.render('/404.mako')

    def connect_to_db(c):
        if c.config is not None and c.db is None:
            c.db = c.config.connect_to_db()
        return c.db
        
if __name__ == "__main__":
    import doctest
    doctest.testmod()
